#include <bits/stdc++.h>

using namespace std;
#define int long long
const int inf = 0x3f3f3f3f;

void solve()
{
	int n, m;
	cin >> n >> m;
	vector<vector<int>> a(n, vector<int>(m));
	int ma = 0;
	for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> a[i][j], ma = max(ma, a[i][j]);
	int x1 = inf, y1 = inf, x2 = inf, y2 = inf;
	int cnt = 0;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (a[i][j] == ma && x1 == inf)
			{
				x1 = i, y1 = j;
				cnt++;
			}
			else if (a[i][j] == ma && x1 != inf && x2 == inf && x1 != i && y1 != j)
			{
				x2 = i, y2 = j;
				cnt++;
			}
			else if (a[i][j] == ma) cnt++;
		}
	}
	int x = x1, y = y2;
	int tmp = cnt;
	if (x == inf || y == inf)
	{
		cout << ma - 1 << endl;
		return;
	}
	for (int i = 0; i < n; i++) if (a[i][y] == ma) cnt--;
	for (int i = 0; i < m; i++) if (a[x][i] == ma) cnt--;
	if (a[x][y] == ma) cnt++;
	if (cnt == 0)
	{
		cout << ma - 1 << endl;
		return;
	}
	x = x2, y = y1;
	cnt = tmp;
	if (x == inf || y == inf)
	{
		cout << ma - 1 << endl;
		return;
	}
	for (int i = 0; i < n; i++) if (a[i][y] == ma) cnt--;
	for (int i = 0; i < m; i++) if (a[x][i] == ma) cnt--;
	if (a[x][y] == ma) cnt++;
	if (cnt == 0)
	{
		cout << ma - 1 << endl;
		return;
	}
	cout << ma << endl;
}

signed main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int _ = 1;
	cin >> _;
	while (_--)
	{
		solve();
	}
	return 0;
}